#include "dkglDesignPattern.h"
#include <algorithm>

namespace DKGL
{

std::list<HeapTracked::RawAddress> *HeapTracked::mAddress = 0;

HeapTracked::~HeapTracked()
{
	if(mAddress && mAddress->size() == 0)
	{
		::operator delete(mAddress);
		mAddress = 0;
	}
}

void *HeapTracked::operator new(size_t size)
{
	if(!mAddress)
		mAddress = new std::list<RawAddress>;
	void *memPtr = ::operator new(size);
	mAddress->push_back(memPtr);
	return memPtr;
}

void HeapTracked::operator delete(void *ptr)
{
	if(!mAddress)
		return;
	
	std::list<RawAddress>::iterator it = 
		std::find(mAddress->begin(), mAddress->end(), ptr);

	if(it!=mAddress->end()){
		mAddress->erase(it);
		::operator delete(ptr);
	}else{
		throw("Miss Address");
	}
}

bool HeapTracked::isOnHeap() const
{
	if(!mAddress)
		return false;

	const void *rawAddress = dynamic_cast<const void*>(this);

	std::list<RawAddress>::iterator it = 
		std::find(mAddress->begin(), mAddress->end(), rawAddress);

	return it!=mAddress->end(); 
}
}